﻿using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace YTBZ.PUB.COMMON
{
    public class PasswordKey
    {
        public static void Main(string[] args)
        {
            try
            {

                //MD5加密
                Console.WriteLine(encryptMD5("yy1yy1"));

                //Base64加密
                string s = "xxx";
                Console.WriteLine("原文本:" + s);
                string v = encode64(Encoding.UTF8.GetBytes(s));//加密
                Console.WriteLine("Base64加密:" + v);
                byte[] key = decode64(v);//解密
                Console.WriteLine("Base64解密:" + Encoding.UTF8.GetString(key));
                //ARC4算法,内包含Base64二次加密
                string z = "123456";
                Console.WriteLine("源密码:" + z);
                Console.WriteLine("ARC4算法加密:" + encryptPwd(z));//加密密码
                Console.WriteLine("ARC4算法解密:" + decryptPwd(encryptPwd(z)));//加密在解密
                Console.Read();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        ///  使用md5进行加密（不可逆）
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string encryptMD5(string value)
        {
            string result = "";
            if (value == null)
            {
                value = "";
            }
            try
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                byte[] buff = System.Text.Encoding.UTF8.GetBytes(value);
                byte[] keyhash = hashmd5.ComputeHash(buff);
                result = System.Text.Encoding.UTF8.GetString(keyhash);
                hashmd5 = null;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return result;
        }

        /// <summary>
        /// byte[]转换为16进制
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byte2hex(byte[] bytes)
        {
            string result = "";
            for (int n = 0; n < bytes.Length; n++)
            {
                result += bytes[n].ToString("X2");

            }
            return result.ToUpper();
        }

        /// <summary>
        /// 获取密钥
        /// </summary>
        /// <returns></returns>
        private static ICipherParameters getkey()
        {
            string encKey = "tyX+dyNeTgKFXZw1toui5w==";
            KeyParameter kp = new KeyParameter(decode64(encKey));
            return kp;
        }

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="b">内容</param>
        /// <returns></returns>
        private static string encode64(byte[] b)
        {
            return Convert.ToBase64String(b);
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="b">加密内容</param>
        /// <returns></returns>
        private static byte[] decode64(string s)
        {
            return Convert.FromBase64String(s);
        }


        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="str">加密内容</param>
        /// <param name="ari">bouncycastle （1.2.840.113549.3.4）ARC4算法</param>
        /// <param name="provider"></param>
        /// <returns></returns>
        public static byte[] encrypt(ICipherParameters kp, byte[] str, string ari)
        {

            CipherKeyGenerator h1 = new CipherKeyGenerator();

            IBufferedCipher cp = null;
            try
            {
                cp = CipherUtilities.GetCipher(ari);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            try
            {
                cp.Init(true, kp);//加密
            }
            catch (InvalidKeyException e)
            {
                Console.WriteLine(e.StackTrace);
            }
            byte[] encode = null;
            try
            {
                encode = cp.DoFinal(str);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            return encode;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="str">加密内容</param>
        /// <param name="ari">bouncycastle （1.2.840.113549.3.4）ARC4算法</param>
        /// <param name="provider"></param>
        /// <returns></returns>
        public static byte[] decrypt(ICipherParameters kp, byte[] str, string ari)
        {
            CipherKeyGenerator h1 = new CipherKeyGenerator();

            IBufferedCipher cp = null;
            try
            {
                cp = CipherUtilities.GetCipher(ari);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            try
            {
                cp.Init(false, kp);  //解密
            }
            catch (InvalidKeyException e)
            {
                Console.WriteLine(e.StackTrace);
            }
            byte[] encode = null;
            try
            {
                encode = cp.DoFinal(str);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            return encode;
        }

        /// <summary>
        /// 加密密码
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        public static string encryptPwd(string a)
        {
            byte[] bEnpriv = null;
            try
            {
                bEnpriv = Encoding.UTF8.GetBytes(a);
                bEnpriv = encrypt(getkey(), bEnpriv, "1.2.840.113549.3.4");
            }
            catch (IOException e)
            {
                Console.WriteLine(e.StackTrace);
            }
            return encode64(bEnpriv);//Base64加密
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        public static string decryptPwd(string a)
        {
            byte[] bEnpriv = null;
            try
            {
                bEnpriv = decode64(a);//Base64解密
                bEnpriv = decrypt(getkey(), bEnpriv,
                        "1.2.840.113549.3.4");
            }
            catch (IOException e)
            {
                Console.WriteLine(e.StackTrace);
            }
            return Encoding.UTF8.GetString(bEnpriv);
        }
    }
}
